<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>dom节点查找</title>
</head>
<body>

	<div id="div1">
		<div id="div11">查找两个节点的最近的一个共同父节点，可以包括节点自身</div>
		<div id="div12">12</div>
	</div>
	<div id="div2">
		<div id="div21">查找两个节点的最近的一个共同父节点，可以包括节点自身</div>
		<div id="div22">22</div>
	</div>
<script>
const dom1 = document.querySelector('#div1');
const dom2 = document.querySelector('#div2');

const dom11 = document.querySelector('#div11');
const dom12 = document.querySelector('#div12');
const dom21 = document.querySelector('#div21');
const dom22 = document.querySelector('#div22');
</script>

<script type="text/javascript">
function commonParentNode(oNode1, oNode2) {
	if (oNode1.contains(oNode2)) return oNode1;
	if (oNode2.contains(oNode1)) return oNode2;
	let parent1 = oNode1.parentNode
	let parent2 = oNode2.parentNode
	while (parent1 || parent2) {
		if (parent1.contains(oNode2)) return parent1;
		if (parent2.contains(oNode1)) return parent2;
		// 如果都没找到,则继续向上查找
		parent1 = parent1.parentNode;
		parent2 = parent2.parentNode;
	}
}
console.log(commonParentNode(dom1, dom22));
</script>
</body>
</html>